package com.hziee.graduate.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hziee.graduate.ticket.dao.*;
import com.hziee.graduate.ticket.dto.R;
import com.hziee.graduate.ticket.entity.*;
import com.hziee.graduate.ticket.service.ScheduleService;
import com.hziee.graduate.ticket.utils.BeanConvertUtil;
import com.hziee.graduate.ticket.utils.DateUtils;
import com.hziee.graduate.ticket.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.krb5.internal.Ticket;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service("scheduleService")
public class ScheduleServiceImpl extends ServiceImpl<ScheduleDao, Schedule> implements ScheduleService {

    @Resource
    private ScheduleDao scheduleDao;

    @Resource
    private RegionDao regionDao;

    @Resource
    private CinemaDao cinemaDao;

    @Resource
    private MovieDao movieDao;

    @Resource
    private RoomDao roomDao;

    @Resource
    private SeatDao seatDao;

    @Resource
    private SeatScheduleDao seatScheduleDao;

    @Resource
    private TicketsDao ticketsDao;

    @Override
    @Transactional
    public R<List<ScheduleVO>> getScheduleByDate(Map<String, Object> map) {
        // 查出想要的数据
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("date",map.get("date").toString());
        queryMap.put("cinema_id",map.get("cinemaId").toString());
        queryMap.put("del_flag",0);
        List<Schedule> schedules = scheduleDao.selectByMap(queryMap);
        List<ScheduleVO> scheduleVOS = BeanConvertUtil.converList(schedules, ScheduleVO.class);
        for (ScheduleVO item : scheduleVOS) {
            // 填充每部电影的名字
            Movie movie = movieDao.selectById(item.getMovieId());
            item.setMovieName(movie.getMovieName());
            item.setMovieDuring(movie.getMovieDuring());
            // 获取影厅信息
            Room roomById = roomDao.selectOne(new QueryWrapper<Room>().eq("room_id", item.getRoomId()));
            //影院名字
            item.setRoomName(roomById.getRoomName());
            //影院类别
            item.setRoomType(roomById.getRoomType());
        }
        return R.success(scheduleVOS);
    }

    @Override
    @Transactional
    public R<Schedule> delScheduleById(Long scheduleId) {
        // 判断排班是否已经有人订票了
        List<Tickets> ticketList = ticketsDao.selectList(new QueryWrapper<Tickets>().eq("schedule_id", scheduleId));
        // 如果已经有人订票就不能删除了
        if(ticketList.size() > 0) {
            return R.error("排班已经有人订票了");
        }else{
            // 如果没有人订票则是可以删除的
            remove(new QueryWrapper<Schedule>().eq("schedule_id",scheduleId));
            // 删除排班及排班座位表
            seatScheduleDao.delete(new QueryWrapper<SeatSchedule>().eq("schedule_id",scheduleId));
            return R.success("排班删除成功");
        }

    }

    @Override
    @Transactional
    public R<Schedule> addSchedule(Map<String, Object> map) {
        //添加排班
        Schedule schedule = new Schedule();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(map.get("date").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        schedule.setDate(simpleDateFormat.format(date));
        schedule.setCinemaId(Long.parseLong(map.get("cinemaId").toString()));
        schedule.setStart(Integer.parseInt(map.get("start").toString()));
        schedule.setEnd(Integer.parseInt(map.get("end").toString()));
        schedule.setCreateTime(DateUtils.getCurrentYMDHMSStr());
        schedule.setMovieId(Long.parseLong(map.get("movieId").toString()));
        schedule.setCreatePerson(Long.parseLong(map.get("userId").toString()));
        schedule.setRoomId(Long.parseLong(map.get("roomId").toString()));
        int insert = scheduleDao.insert(schedule);
        // 添加完排班之后，将座位复制出来一份和排班产生关联
        List<Seat> seats = seatDao.selectList(new QueryWrapper<Seat>().eq("room_id", Long.parseLong(map.get("roomId").toString())));
        List<SeatSchedule> seatScheduleList = BeanConvertUtil.converList(seats,SeatSchedule.class);
        seatScheduleList.forEach(item -> {
            item.setScheduleId(schedule.getScheduleId());
        });
        seatScheduleDao.insertBatch(seatScheduleList);
        return R.success(schedule);
    }

    @Override
    public R<List<CascaderVO>> getCascaderOptionByMovie(Long movieId, String date, String cityname) {
        ArrayList<CascaderVO> CascaderVOs = new ArrayList<>();
        List<AreaVO> areaByCity = regionDao.getAreaByCity(cityname);
        // 获得地区
        areaByCity.forEach(item -> {
            CascaderVOs.add(new CascaderVO(item.getAreaName(),item.getAreaId()));
        });
        // 获得地区下面的影院
        CascaderVOs.forEach(item -> {
            List<Cinema> cinemaByRegionId = cinemaDao.getCinemaByRegionId(Integer.parseInt(item.getValue().toString()));
            cinemaByRegionId.forEach(item2 -> {
                item.getChildren().add(new CascaderVO(item2.getCinemaName(),item2.getCinemaId()));
            });
        });
        // 获取影院下面的影厅
        CascaderVOs.forEach(item -> {
            item.getChildren().forEach(item2 -> {
                List<RoomVO> roomByScheduleList = roomDao.getRoomBySchedule(movieId,date,Long.parseLong(item2.getValue().toString()));
                roomByScheduleList.forEach(item3 -> {
                    String timeStr = item3.getRoomName()+"("+DateUtils.formatMinune(item3.getStart(),item3.getEnd())+")";
                    item2.getChildren().add(new CascaderVO(timeStr,item3.getScheduleId()));
                });
            });
        });
        return R.success(CascaderVOs);
    }

    @Override
    public R<List<EntryVO>> getEntryInfoByCinemaId(Long cinemaId) {
        List<EntryVO> EntryVOs = new ArrayList();
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        int minute = now.getMinute();
        int distance = hour * 60 + minute;

        // 获取该天所有的排班
        List<Schedule> schedules = scheduleDao.selectList(new QueryWrapper<Schedule>()
                .eq("cinema_id", cinemaId)
                .eq("date", DateUtils.getCurrentYMDStr())
        );
        schedules.forEach(item -> {
            Integer start = item.getStart();
            Integer beforeStart30 = item.getStart() - 30;
            if(distance>= beforeStart30 && distance <= start) {
                // 说明该排班正在检票
                EntryVO entryVO = new EntryVO();
                // 获取检票数
                int checkNum = ticketsDao.selectList(new QueryWrapper<Tickets>()
                        .eq("schedule_id", item.getScheduleId())
                        .eq("check_status", 1)
                ).size();
                // 获得影院的信息
                Room roomById = roomDao.selectOne(
                        new QueryWrapper<Room>()
                                .eq("room_id", item.getRoomId())
                );
                String roomName = roomById.getRoomName();
                Integer roomContain = roomById.getRoomContain();

                entryVO.setCheckNum(checkNum);
                entryVO.setDistanceTime(start - distance);
                entryVO.setRoomName(roomName);
                entryVO.setRoomContain(roomContain);

                EntryVOs.add(entryVO);
            }
        });

        return R.success(EntryVOs);
    }
}

